package com.acme.bankapp.service.network;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import com.acme.bankapp.domain.bank.Bank;
import com.acme.bankapp.domain.bank.Client;
import com.acme.bankapp.service.bank.BankFeederService;
import com.acme.bankapp.service.bank.BankService;

public class BankServer {
	static final int port = 6666;
	
	static final String BANK_SERVER_PROMPT = "Welcome to BankApp. List of available commands:\n getc - get clients\n geta - get accounts\n add <feed> - add client\n shutdown - shutdown server and exit client\n";
	
	BankService bs = new BankService();
	Bank bank;
	
	public void run(Bank bank) {
		this.bank = bank;
		System.out.println("Running server...");
		try (ServerSocket sockFactory = new ServerSocket(port);
				Socket socket = sockFactory.accept();
				ObjectOutputStream socketWriter = new ObjectOutputStream(socket.getOutputStream());
				ObjectInputStream socketReader = new ObjectInputStream(socket.getInputStream());) {
			String request, response;
			System.out.println(socket.getRemoteSocketAddress().toString() + " connected");
			socketWriter.writeObject(BANK_SERVER_PROMPT);
			socketWriter.flush();
			
			while (((request = (String) socketReader.readObject()) != null) && !"shutdown".equals(request)) {
				System.out.println(request);
				response = processRequest(request);
				socketWriter.writeObject(response);
				socketWriter.flush();
			}
			System.out.println("Shutting down");
			socketWriter.writeObject("Goodbye");
			socketWriter.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			System.out.println("couldn't convert string");
		}
	}
	
	String processRequest (final String request) {
		String response;
		String [] splitRequest = request.split("\\s+");
		
		switch (splitRequest[0]) {
		case "getc":
			response = bs.getClientsListAsString(this.bank);
			break;
		case "geta":
			response = bs.getAccountsListAsString(this.bank);
			break;
		case "add":
			Client cl = bs.addClient(this.bank, BankFeederService.makeClientFromString(splitRequest[1]));
			response = cl.getClientSalutation() + " added\n";
			break;
		default:
			response = request;
			break;
		}
		
		return response;
	}
}
